package com.vehiclemanagement.service.impl;

import com.vehiclemanagement.mapper.*;
import com.vehiclemanagement.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.*;

/**
 * 报表分析服务实现类
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private VehicleMapper vehicleMapper;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private VehicleUseRecordMapper vehicleUseRecordMapper;

    @Autowired
    private FuelRefillMapper fuelRefillMapper;

    @Autowired
    private MaintenanceRecordMapper maintenanceRecordMapper;

    @Autowired
    private VehicleInspectionMapper vehicleInspectionMapper;

    @Autowired
    private TrafficViolationMapper trafficViolationMapper;

    @Autowired
    private AccidentRecordMapper accidentRecordMapper;

    @Autowired
    private ETCCardMapper etcCardMapper;

    @Autowired
    private ETCPassageMapper etcPassageMapper;

    @Autowired
    private ETCParkingMapper etcParkingMapper;

    @Override
    public List<Map<String, Object>> getVehicleUsageStatistics(Long vehicleId, LocalDateTime startTime, LocalDateTime endTime) {
        log.info("获取车辆使用统计数据: vehicleId={}, startTime={}, endTime={}", vehicleId, startTime, endTime);
        return reportMapper.getVehicleUsageStatistics(vehicleId, startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getVehicleCostStatistics(Long vehicleId, LocalDateTime startTime, LocalDateTime endTime) {
        log.info("获取车辆费用统计数据: vehicleId={}, startTime={}, endTime={}", vehicleId, startTime, endTime);
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取加油成本
        List<Map<String, Object>> fuelStats = getFuelStatistics(null, null);
        Double fuelCost = 0.0;
        if (fuelStats != null && !fuelStats.isEmpty()) {
            for (Map<String, Object> stat : fuelStats) {
                fuelCost += Double.parseDouble(stat.getOrDefault("total_price", "0").toString());
            }
        }
        Map<String, Object> fuelMap = new HashMap<>();
        fuelMap.put("cost_type", "加油费用");
        fuelMap.put("cost_value", fuelCost);
        result.add(fuelMap);
        
        // 获取ETC通行成本
        List<Map<String, Object>> passageStats = getETCStatistics(null, null, null);
        Double passageCost = 0.0;
        if (passageStats != null && !passageStats.isEmpty()) {
            for (Map<String, Object> stat : passageStats) {
                passageCost += Double.parseDouble(stat.getOrDefault("total_fee", "0").toString());
            }
        }
        Map<String, Object> passageMap = new HashMap<>();
        passageMap.put("cost_type", "ETC通行费用");
        passageMap.put("cost_value", passageCost);
        result.add(passageMap);
        
        // 获取ETC停车成本
        List<Map<String, Object>> parkingStats = reportMapper.getETCParkingStatistics(null, null);
        Double parkingCost = 0.0;
        if (parkingStats != null && !parkingStats.isEmpty()) {
            for (Map<String, Object> stat : parkingStats) {
                parkingCost += Double.parseDouble(stat.getOrDefault("total_fee", "0").toString());
            }
        }
        Map<String, Object> parkingMap = new HashMap<>();
        parkingMap.put("cost_type", "ETC停车费用");
        parkingMap.put("cost_value", parkingCost);
        result.add(parkingMap);
        
        // 获取维修保养成本
        List<Map<String, Object>> maintenanceStats = getMaintenanceStatistics(null, null, null);
        Double maintenanceCost = 0.0;
        if (maintenanceStats != null && !maintenanceStats.isEmpty()) {
            for (Map<String, Object> stat : maintenanceStats) {
                maintenanceCost += Double.parseDouble(stat.getOrDefault("total_cost", "0").toString());
            }
        }
        Map<String, Object> maintenanceMap = new HashMap<>();
        maintenanceMap.put("cost_type", "维修保养费用");
        maintenanceMap.put("cost_value", maintenanceCost);
        result.add(maintenanceMap);
        
        // 获取年检成本
        List<Map<String, Object>> inspectionStats = getInspectionStatistics(null, null, null);
        Double inspectionCost = 0.0;
        if (inspectionStats != null && !inspectionStats.isEmpty()) {
            for (Map<String, Object> stat : inspectionStats) {
                inspectionCost += Double.parseDouble(stat.getOrDefault("total_cost", "0").toString());
            }
        }
        Map<String, Object> inspectionMap = new HashMap<>();
        inspectionMap.put("cost_type", "年检费用");
        inspectionMap.put("cost_value", inspectionCost);
        result.add(inspectionMap);
        
        // 获取违章成本
        List<Map<String, Object>> violationStats = getViolationStatistics(null, null);
        Double violationCost = 0.0;
        if (violationStats != null && !violationStats.isEmpty()) {
            for (Map<String, Object> stat : violationStats) {
                violationCost += Double.parseDouble(stat.getOrDefault("total_fine", "0").toString());
            }
        }
        Map<String, Object> violationMap = new HashMap<>();
        violationMap.put("cost_type", "交通违章罚款");
        violationMap.put("cost_value", violationCost);
        result.add(violationMap);
        
        // 获取事故成本
        List<Map<String, Object>> accidentStats = getAccidentStatistics(null, null);
        Double accidentCost = 0.0;
        if (accidentStats != null && !accidentStats.isEmpty()) {
            for (Map<String, Object> stat : accidentStats) {
                accidentCost += Double.parseDouble(stat.getOrDefault("total_loss", "0").toString());
            }
        }
        Map<String, Object> accidentMap = new HashMap<>();
        accidentMap.put("cost_type", "事故损失费用");
        accidentMap.put("cost_value", accidentCost);
        result.add(accidentMap);
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getDriverWorkStatistics(Long driverId, LocalDateTime startTime, LocalDateTime endTime) {
        log.info("获取驾驶员工作统计数据: driverId={}, startTime={}, endTime={}", driverId, startTime, endTime);
        return reportMapper.getDriverWorkStatistics(driverId, startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getViolationStatistics(Integer year, Integer month) {
        log.info("获取违章统计数据: year={}, month={}", year, month);
        return reportMapper.getViolationStatistics(year, month);
    }

    @Override
    public List<Map<String, Object>> getAccidentStatistics(Integer year, Integer month) {
        log.info("获取事故统计数据: year={}, month={}", year, month);
        return reportMapper.getAccidentStatistics(year, month);
    }

    @Override
    public List<Map<String, Object>> getFuelStatistics(Integer year, Integer month) {
        log.info("获取加油统计数据: year={}, month={}", year, month);
        return reportMapper.getFuelStatistics(year, month);
    }

    @Override
    public List<Map<String, Object>> getETCStatistics(Integer year, Integer month, Integer type) {
        // 默认统计本年度数据
        if (year == null) {
            year = LocalDateTime.now().getYear();
        }
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        if (type == null || type == 1) {
            // 统计ETC通行费用
            List<Map<String, Object>> passageStats = etcPassageMapper.getETCPassageStatistics(year, month);
            for (Map<String, Object> stat : passageStats) {
                stat.put("type", "通行费");
                result.add(stat);
            }
        }
        
        if (type == null || type == 2) {
            // 统计ETC停车费用
            List<Map<String, Object>> parkingStats = etcParkingMapper.getETCParkingStatistics(year, month);
            for (Map<String, Object> stat : parkingStats) {
                stat.put("type", "停车费");
                result.add(stat);
            }
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getMaintenanceStatistics(Integer year, Integer month, Integer type) {
        log.info("获取维修保养统计数据: year={}, month={}, type={}", year, month, type);
        return reportMapper.getMaintenanceStatistics(year, month);
    }

    @Override
    public List<Map<String, Object>> getInspectionStatistics(Integer year, Integer month, Integer type) {
        log.info("获取年检统计数据: year={}, month={}, type={}", year, month, type);
        return reportMapper.getInspectionStatistics(year, month);
    }

    /**
     * 获取车辆综合分析数据
     *
     * @param vehicleId 车辆ID
     * @return 车辆综合分析数据
     */
    @Override
    public Map<String, Object> getVehicleAnalysis(Long vehicleId) {
        log.info("获取车辆综合分析数据: vehicleId={}", vehicleId);
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取车辆基本信息
        com.vehiclemanagement.entity.Vehicle vehicle = vehicleMapper.selectById(vehicleId);
        if (vehicle != null) {
            Map<String, Object> vehicleInfo = new HashMap<>();
            vehicleInfo.put("id", vehicle.getId());
            vehicleInfo.put("plateNumber", vehicle.getPlateNumber());
            vehicleInfo.put("vehicleType", vehicle.getVehicleType());
            vehicleInfo.put("brand", vehicle.getBrand());
            vehicleInfo.put("model", vehicle.getModel());
            vehicleInfo.put("status", vehicle.getStatus());
            result.put("vehicleInfo", vehicleInfo);
        }
        
        // 获取车辆使用统计
        LocalDateTime startTime = LocalDateTime.now().minusYears(1);
        LocalDateTime endTime = LocalDateTime.now();
        List<Map<String, Object>> usageStatistics = getVehicleUsageStatistics(vehicleId, startTime, endTime);
        result.put("usageStatistics", usageStatistics);
        
        // 获取车辆费用统计
        List<Map<String, Object>> costStatistics = getVehicleCostStatistics(vehicleId, startTime, endTime);
        result.put("costStatistics", costStatistics);
        
        // 获取违章记录数量
        Long violationCount = trafficViolationMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.vehiclemanagement.entity.TrafficViolation>()
                .eq(com.vehiclemanagement.entity.TrafficViolation::getVehicleId, vehicleId)
                .eq(com.vehiclemanagement.entity.TrafficViolation::getDelFlag, 0));
        result.put("violationCount", violationCount);
        
        // 获取事故记录数量
        Long accidentCount = accidentRecordMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.vehiclemanagement.entity.AccidentRecord>()
                .eq(com.vehiclemanagement.entity.AccidentRecord::getVehicleId, vehicleId)
                .eq(com.vehiclemanagement.entity.AccidentRecord::getDelFlag, 0));
        result.put("accidentCount", accidentCount);
        
        return result;
    }

    /**
     * 获取驾驶员综合分析数据
     *
     * @param driverId 驾驶员ID
     * @return 驾驶员综合分析数据
     */
    @Override
    public Map<String, Object> getDriverAnalysis(Long driverId) {
        log.info("获取驾驶员综合分析数据: driverId={}", driverId);
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取驾驶员基本信息
        com.vehiclemanagement.entity.Driver driver = driverMapper.selectById(driverId);
        if (driver != null) {
            Map<String, Object> driverInfo = new HashMap<>();
            driverInfo.put("id", driver.getId());
            driverInfo.put("name", driver.getName());
            driverInfo.put("licenseNumber", driver.getLicenseNumber());
            driverInfo.put("department", driver.getDepartment());
            driverInfo.put("status", driver.getStatus());
            result.put("driverInfo", driverInfo);
        }
        
        // 获取驾驶员工作统计
        LocalDateTime startTime = LocalDateTime.now().minusYears(1);
        LocalDateTime endTime = LocalDateTime.now();
        List<Map<String, Object>> workStatistics = getDriverWorkStatistics(driverId, startTime, endTime);
        result.put("workStatistics", workStatistics);
        
        // 获取违章记录数量
        Long violationCount = trafficViolationMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.vehiclemanagement.entity.TrafficViolation>()
                .eq(com.vehiclemanagement.entity.TrafficViolation::getDriverId, driverId)
                .eq(com.vehiclemanagement.entity.TrafficViolation::getDelFlag, 0));
        result.put("violationCount", violationCount);
        
        // 获取事故记录数量
        Long accidentCount = accidentRecordMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.vehiclemanagement.entity.AccidentRecord>()
                .eq(com.vehiclemanagement.entity.AccidentRecord::getDriverId, driverId)
                .eq(com.vehiclemanagement.entity.AccidentRecord::getDelFlag, 0));
        result.put("accidentCount", accidentCount);
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getCostDistribution(Integer year, Integer month) {
        log.info("获取费用分布统计数据: year={}, month={}", year, month);
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取加油成本
        List<Map<String, Object>> fuelStats = getFuelStatistics(year, month);
        Double fuelCost = 0.0;
        if (fuelStats != null && !fuelStats.isEmpty()) {
            for (Map<String, Object> stat : fuelStats) {
                fuelCost += Double.parseDouble(stat.getOrDefault("total_price", "0").toString());
            }
        }
        Map<String, Object> fuelMap = new HashMap<>();
        fuelMap.put("cost_type", "加油费用");
        fuelMap.put("cost_value", fuelCost);
        result.add(fuelMap);
        
        // 获取ETC通行成本
        List<Map<String, Object>> passageStats = getETCStatistics(year, month, 1);
        Double passageCost = 0.0;
        if (passageStats != null && !passageStats.isEmpty()) {
            for (Map<String, Object> stat : passageStats) {
                passageCost += Double.parseDouble(stat.getOrDefault("total_fee", "0").toString());
            }
        }
        Map<String, Object> passageMap = new HashMap<>();
        passageMap.put("cost_type", "ETC通行费用");
        passageMap.put("cost_value", passageCost);
        result.add(passageMap);
        
        // 获取ETC停车成本
        List<Map<String, Object>> parkingStats = getETCStatistics(year, month, 2);
        Double parkingCost = 0.0;
        if (parkingStats != null && !parkingStats.isEmpty()) {
            for (Map<String, Object> stat : parkingStats) {
                parkingCost += Double.parseDouble(stat.getOrDefault("total_fee", "0").toString());
            }
        }
        Map<String, Object> parkingMap = new HashMap<>();
        parkingMap.put("cost_type", "ETC停车费用");
        parkingMap.put("cost_value", parkingCost);
        result.add(parkingMap);
        
        // 获取维修保养成本
        List<Map<String, Object>> maintenanceStats = getMaintenanceStatistics(year, month, null);
        Double maintenanceCost = 0.0;
        if (maintenanceStats != null && !maintenanceStats.isEmpty()) {
            for (Map<String, Object> stat : maintenanceStats) {
                maintenanceCost += Double.parseDouble(stat.getOrDefault("total_cost", "0").toString());
            }
        }
        Map<String, Object> maintenanceMap = new HashMap<>();
        maintenanceMap.put("cost_type", "维修保养费用");
        maintenanceMap.put("cost_value", maintenanceCost);
        result.add(maintenanceMap);
        
        // 获取年检成本
        List<Map<String, Object>> inspectionStats = getInspectionStatistics(year, month, null);
        Double inspectionCost = 0.0;
        if (inspectionStats != null && !inspectionStats.isEmpty()) {
            for (Map<String, Object> stat : inspectionStats) {
                inspectionCost += Double.parseDouble(stat.getOrDefault("total_cost", "0").toString());
            }
        }
        Map<String, Object> inspectionMap = new HashMap<>();
        inspectionMap.put("cost_type", "年检费用");
        inspectionMap.put("cost_value", inspectionCost);
        result.add(inspectionMap);
        
        // 获取违章成本
        List<Map<String, Object>> violationStats = getViolationStatistics(year, month);
        Double violationCost = 0.0;
        if (violationStats != null && !violationStats.isEmpty()) {
            for (Map<String, Object> stat : violationStats) {
                violationCost += Double.parseDouble(stat.getOrDefault("total_fine", "0").toString());
            }
        }
        Map<String, Object> violationMap = new HashMap<>();
        violationMap.put("cost_type", "交通违章罚款");
        violationMap.put("cost_value", violationCost);
        result.add(violationMap);
        
        // 获取事故成本
        List<Map<String, Object>> accidentStats = getAccidentStatistics(year, month);
        Double accidentCost = 0.0;
        if (accidentStats != null && !accidentStats.isEmpty()) {
            for (Map<String, Object> stat : accidentStats) {
                accidentCost += Double.parseDouble(stat.getOrDefault("total_loss", "0").toString());
            }
        }
        Map<String, Object> accidentMap = new HashMap<>();
        accidentMap.put("cost_type", "事故损失费用");
        accidentMap.put("cost_value", accidentCost);
        result.add(accidentMap);
        
        return result;
    }

    @Override
    public Map<String, Object> getOperationCostAnalysis(Integer year) {
        log.info("获取总体运营成本分析: year={}", year);
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取费用分布统计数据
        List<Map<String, Object>> costDistribution = getCostDistribution(year, null);
        result.put("costDistribution", costDistribution);
        
        // 计算总成本
        Double totalCost = 0.0;
        for (Map<String, Object> cost : costDistribution) {
            Double value = (Double) cost.get("cost_value");
            if (value != null) {
                totalCost += value;
            }
        }
        result.put("totalCost", totalCost);
        
        // 获取按月份统计的运营成本数据
        List<Map<String, Object>> monthlyCosts = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            List<Map<String, Object>> monthCost = getCostDistribution(year, i);
            Double monthTotalCost = 0.0;
            for (Map<String, Object> cost : monthCost) {
                Double value = (Double) cost.get("cost_value");
                if (value != null) {
                    monthTotalCost += value;
                }
            }
            
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", i);
            monthData.put("cost", monthTotalCost);
            monthlyCosts.add(monthData);
        }
        result.put("monthlyCosts", monthlyCosts);
        
        return result;
    }
} 